#include "chatbox.h"
#include "chatbubble.h"
#include <QScrollArea>
#include <QHBoxLayout>
#include <QLabel>
#include "pages/chat/chatwidget.h"

ChatBox::ChatBox(QWidget *parent)
    : QStackedWidget{parent}
{
    setStyleSheet("border: none;");
}

void ChatBox::addFriend(const QString &user_name)
{
    if(pages.count(user_name) != 0){
        return ;
    }
    QScrollArea *s = new QScrollArea;
    s->setWidgetResizable(true);
    QWidget *content_widget = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(5);
    layout->addSpacerItem(new QSpacerItem(1,1,QSizePolicy::Fixed,QSizePolicy::Expanding));
    content_widget->setLayout(layout);
    s->setWidget(content_widget);
    pages.insert(user_name,s);
    addWidget(s);
}

void ChatBox::changeChatPage(const QString &user_name)
{
    current_user_name = user_name;
    setCurrentIndex(indexOf(pages[user_name]));
}

void ChatBox::appendMessage(const QString &message,Qt::AlignmentFlag alignment)
{
    QScrollArea *s = (QScrollArea *)currentWidget();
    QVBoxLayout *layout = (QVBoxLayout *)s->widget()->layout();
    ChatBubble *bubble =new ChatBubble;
    bubble->setChatText(message,s->width()-20);
    layout->addWidget(new QLabel("我"),0,alignment);
    layout->addWidget(bubble,0,alignment);
}

void ChatBox::appendMessageTo(const QString &user_name, const QString &message, Qt::AlignmentFlag alignment)
{
    QScrollArea *s = (QScrollArea *)pages[user_name];
    QVBoxLayout *layout = (QVBoxLayout *)s->widget()->layout();
    ChatBubble *bubble =new ChatBubble;
    bubble->setChatText(message,s->width()-20);
    layout->addWidget(new QLabel(user_name),0,alignment);
    layout->addWidget(bubble,0,alignment);
}
